

import React from 'react';
import PropTypes from 'prop-types';
import {injectIntl, language} from './intl';
import {Card, Button, Form, Row, Col, Collapse, message, Spin, Table} from 'antd';
const Panel = Collapse.Panel;
import {FORM_OPTIONS, PAGE, TABLE, FORM_BIG_OPTIONS, FORM_ROW_OPTIONS} from '../constants';
import routes from './routes';
const FormItem = Form.Item;
import styles from './style.css';
import Return from '../common/Return';
import {formatAmount, conventEnumValueToString, formatPercent} from '../utils';
import {currency} from '../Enum';
import FileUpload from './FileUpload';
import Ellipsis from 'ant-design-pro/lib/Ellipsis';
import {getDetailRepeat} from './api';
const bodyStyle = {
    padding: 0
};
export class UpPiPanel extends React.PureComponent {
    static getDerivedStateFromProps(props, state) {
        if(state.isDefault && props.detail && props.detail.id)
            return {
                remark: props.detail.remark,
                // businessType: props.detail.businessType,
                department: props.detail.department,
                isDefault: false,
            };

        return null;
    }
    state = {
        visible: false,
        loading: false,
        isValidate: false,
        hasOperat: false,
        financeApproveOpinion: '',
        remark: '',
        isDefault: true,
        selectedRowKeys: [],
        isRepeat: false
    }

    componentDidMount() {
        this.props.init();
        this.ismounted = true;
    }
    componentWillUnmount() {
        this.ismounted = false;
        this.props.onUmount();
    }

    handleFilterChange = (value, name) => {
        if(this.state.hasOperat)
            this.setState({[name]: value});
        else
            this.setState({
                hasOperat: true,
                [name]: value
            });
    }

    handleStatusChange = e => {
        if(this.state.hasOperat)
            this.setState({isApproved: e.target.value});
        else
            this.setState({
                hasOperat: true,
                isApproved: e.target.value
            });
    }

    submit = () => {
        const {attachments = []} = this.props.conditions;
        if(attachments.length < 1) {
            this.setState({isValidate: true});
            return message.warn(this.props.intl.formatMessage({
                id: 'upPiPanel.attachments.validate',
                defaultMessage: '附件必须有东西'
            }));
        }
        this.setState({loading: true});
        this.props.onClickUpPi(attachments).then(success => {
            if(this.ismounted && !success)
                this.setState({loading: false});
        });
    }
    onChangeUpload = data => {
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        this.props.updateAttachments(data);
    }
    onClickRepeatBtn = () => {
        this.setState({
            isFetching: true,
            isRepeat: true
        });
        getDetailRepeat(this.props.conditions.id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        isFetching: false,
                        details: res.data,
                    });
                else
                    this.setState(({
                        isFetching: false,
                        isRepeat: false
                    }));
            });
    }
    onClickReductionBtn = () => {
        this.setState({
            isRepeat: false
        });
    }
    render() {
        const languageIntl = language;
        const {details = [], attachments = []} = this.props.conditions;
        const newdetails = this.state.isRepeat ? this.state.details : details;
        const columns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'upPiPanel.column.code',
                    defaultMessage: '单据编号'
                }),
                dataIndex: 'code',
                width: 180,
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'upPiPanel.column.vin',
                    defaultMessage: 'VIN'
                }),
                dataIndex: 'vin',
                width: 170,
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'upPiPanel.column.productCategoryCode',
                    defaultMessage: '车型'
                }),
                dataIndex: 'productCategoryCode',
                width: 150,
                render: text => <span title={text}><Ellipsis length={20}>{text}</Ellipsis></span>
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'upPiPanel.column.partCode',
                    defaultMessage: '备件编号'
                }),
                dataIndex: 'partCode',
                width: languageIntl === 'pt-PT' ? 260 : 195,
                render: text => <span title={text}><Ellipsis length={20}>{text}</Ellipsis></span>
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'upPiPanel.column.partName',
                    defaultMessage: '备件名称'
                }),
                dataIndex: 'partName',
                width: 280,
                render: text => <span title={text}><Ellipsis length={28}>{text}</Ellipsis></span>
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'upPiPanel.column.isCaused',
                    defaultMessage: '是否主损件'
                }),
                dataIndex: 'isCaused',
                width: 280,
                render: text => text ? 'Y' : 'N'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'upPiPanel.column.quantity',
                    defaultMessage: '备件数量'
                }),
                dataIndex: 'quantity',
                className: styles.textAlign,
                width: 150,
                render: text => formatAmount(text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'upPiPanel.column.currency',
                    defaultMessage: ' 币种'
                }),
                dataIndex: 'currency',
                width: 120,
                render: text => conventEnumValueToString(currency, text)
            }
        ];
        if(!this.props.isMoneyVisible)
            columns.splice(7, 0,
                {
                    title: this.props.intl.formatMessage({
                        id: 'upPiPanel.column.price',
                        defaultMessage: '单价'
                    }),
                    dataIndex: 'price',
                    className: styles.textAlign,
                    width: 150,
                    render: text => formatAmount(text)
                },
                {
                    title: this.props.intl.formatMessage({
                        id: 'upPiPanel.column.materialFee',
                        defaultMessage: '材料费'
                    }),
                    dataIndex: 'materialFee',
                    className: styles.textAlign,
                    width: 150,
                    render: text => formatAmount(text)
                },
                {
                    title: this.props.intl.formatMessage({
                        id: 'upPiPanel.column.mgmtFee',
                        defaultMessage: '管理费'
                    }),
                    dataIndex: 'mgmtFee',
                    className: styles.textAlign,
                    width: 150,
                    render: text => formatAmount(text)
                },
                {
                    title: this.props.intl.formatMessage({
                        id: 'upPiPanel.column.laborFee',
                        defaultMessage: '工时费'
                    }),
                    dataIndex: 'laborFee',
                    className: styles.textAlign,
                    width: languageIntl === 'pt-PT' ? 190 : 120,
                    render: text => formatAmount(text)
                },
                {
                    title: this.props.intl.formatMessage({
                        id: 'upPiPanel.column.accessoryFee',
                        defaultMessage: '辅料费'
                    }),
                    dataIndex: 'accessoryFee',
                    className: styles.textAlign,
                    width: languageIntl === 'pt-PT' ? 180 : 120,
                    render: text => formatAmount(text)
                },
                {
                    title: this.props.intl.formatMessage({
                        id: 'upPiPanel.column.totalFee',
                        defaultMessage: '费用合计'
                    }),
                    dataIndex: 'totalFee',
                    sorter: true,
                    width: 130,
                    className: styles.textAlign,
                    render: text => formatAmount(text)
                });
        if(!this.props.isDealerUser && !this.props.isMoneyVisible) {
            columns.splice(9, 0,
                {
                    title: this.props.intl.formatMessage({
                        id: 'upPiPanel.column.mgmtFeeRate',
                        defaultMessage: '管理费率'
                    }),
                    dataIndex: 'mgmtFeeRate',
                    className: styles.textAlign,
                    width: 150,
                    render: text => formatPercent(text)
                });
            columns.splice(11, 0,
                {
                    title: this.props.intl.formatMessage({
                        id: 'upPiPanel.column.laborPrice',
                        defaultMessage: '工时单价'
                    }),
                    dataIndex: 'laborPrice',
                    className: styles.textAlign,
                    width: languageIntl === 'pt-PT' ? 190 : 120,
                    render: text => formatAmount(text)
                });
        }
        const rowSelection = {
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: selectedRowKeys => {
                this.setState({
                    selectedRowKeys
                });
            }
        };
        return (
            <div className={styles.detail}>
                <Spin spinning={this.props.loading || this.state.loading}>
                    <Card bodyStyle={bodyStyle}>
                        <Collapse defaultActiveKey="1" bordered={false}>
                            <Panel header={this.props.intl.formatMessage({
                                id: 'upPiPanel.detail.panel',
                                defaultMessage: '结算单详情'
                            })} key="1" forceRender>
                                <Form className="form-standard">
                                    <Card
                                        title={this.props.intl.formatMessage({
                                            id: 'upPiPanel.order.title',
                                            defaultMessage: '单据信息'
                                        })}>
                                        <Row>
                                            <Col {...FORM_OPTIONS.col}>
                                                <FormItem {...FORM_OPTIONS.item}
                                                    label={this.props.intl.formatMessage({
                                                        id: 'upPiPanel.info.code',
                                                        defaultMessage: '结算单号'
                                                    })}>
                                                    {this.props.conditions.code}
                                                </FormItem>
                                            </Col>
                                            {this.props.isDealerUser ? null
                                                : <Col {...FORM_OPTIONS.col}>
                                                    <FormItem {...FORM_OPTIONS.item}
                                                        label={this.props.intl.formatMessage({
                                                            id: 'upPiPanel.info.dealerCode',
                                                            defaultMessage: '总代编号'
                                                        })}>
                                                        {this.props.conditions.dealerCode}
                                                    </FormItem>
                                                </Col>}
                                            {/* <Col {...FORM_OPTIONS.col}>
                                                <FormItem {...FORM_OPTIONS.item}
                                                    validateStatus={this.state.isValidate && !this.props.conditions.businessType ? 'error' : null}
                                                    required
                                                    label={this.props.intl.formatMessage({
                                                        id: 'upPiPanel.info.businessType',
                                                        defaultMessage: '业务类型'
                                                    })}>
                                                    {conventEnumValueToString(transportType, this.props.conditions.businessType)}
                                                </FormItem>
                                            </Col> */}
                                            {!this.props.isMoneyVisible &&
                                            <Col {...FORM_OPTIONS.col}>
                                                <FormItem {...FORM_OPTIONS.item}
                                                    label={this.props.intl.formatMessage({
                                                        id: 'upPiPanel.info.materialFee',
                                                        defaultMessage: '材料费'
                                                    })}>
                                                    {formatAmount(this.props.conditions.materialFee)}
                                                </FormItem>
                                            </Col>}
                                            {!this.props.isMoneyVisible &&
                                            <Col {...FORM_OPTIONS.col}>
                                                <FormItem {...FORM_OPTIONS.item}
                                                    label={this.props.intl.formatMessage({
                                                        id: 'upPiPanel.info.mgmtFee',
                                                        defaultMessage: '配件管理费'
                                                    })}>
                                                    {formatAmount(this.props.conditions.mgmtFee)}
                                                </FormItem>
                                            </Col>}
                                            {!this.props.isMoneyVisible &&
                                            <Col {...FORM_OPTIONS.col}>
                                                <FormItem {...FORM_OPTIONS.item}
                                                    label={this.props.intl.formatMessage({
                                                        id: 'upPiPanel.info.laborFee',
                                                        defaultMessage: '工时费'
                                                    })}>
                                                    {formatAmount(this.props.conditions.laborFee)}
                                                </FormItem>
                                            </Col>}
                                            {!this.props.isMoneyVisible &&
                                            <Col {...FORM_OPTIONS.col}>
                                                <FormItem {...FORM_OPTIONS.item}
                                                    label={this.props.intl.formatMessage({
                                                        id: 'upPiPanel.info.suppleMaterialFee',
                                                        defaultMessage: '辅料费'
                                                    })}>
                                                    {formatAmount(this.props.conditions.suppleMaterialFee)}
                                                </FormItem>
                                            </Col>}
                                            {/* <Col {...FORM_OPTIONS.col}>
                                                <FormItem {...FORM_OPTIONS.item}
                                                    label={this.props.intl.formatMessage({
                                                        id: 'upPiPanel.info.outFee',
                                                        defaultMessage: '外出费用'
                                                    })}>
                                                    {formatAmount(this.props.conditions.outFee)}
                                                </FormItem>
                                            </Col> */}
                                            {!this.props.isMoneyVisible &&
                                            <Col {...FORM_OPTIONS.col}>
                                                <FormItem {...FORM_OPTIONS.item}
                                                    label={this.props.intl.formatMessage({
                                                        id: 'upPiPanel.info.totalFee',
                                                        defaultMessage: '费用合计'
                                                    })}>
                                                    {formatAmount(this.props.conditions.totalFee)}
                                                </FormItem>
                                            </Col>}
                                            <Col {...FORM_OPTIONS.col}>
                                                <FormItem {...FORM_OPTIONS.item}
                                                    label={this.props.intl.formatMessage({
                                                        id: 'upPiPanel.info.currency',
                                                        defaultMessage: '币种'
                                                    })}>
                                                    {conventEnumValueToString(currency, this.props.conditions.currency)}
                                                </FormItem>
                                            </Col>
                                            <Col {...FORM_OPTIONS.col}>
                                                <FormItem className={styles.multiLabel} {...FORM_OPTIONS.item}
                                                    label={this.props.intl.formatMessage({
                                                        id: 'upPiPanel.info.department',
                                                        defaultMessage: '报销部门'
                                                    })}>
                                                    {this.props.conditions.department}
                                                </FormItem>
                                            </Col>
                                        </Row>
                                        <Row>
                                            <FormItem {...FORM_ROW_OPTIONS.item} label={this.props.intl.formatMessage({
                                                id: 'upPiPanel.info.remark',
                                                defaultMessage: '备注'
                                            })}>
                                                {this.props.conditions.remark}
                                            </FormItem>
                                        </Row>
                                    </Card>
                                    <Card
                                        title={<Row><Col>{this.props.intl.formatMessage({
                                            id: 'detail.details.title',
                                            defaultMessage: '清单列表'
                                        })}{' '}
                                        {this.state.isRepeat ? <Button
                                            className={styles.selectRepeatBtn}
                                            size="small"
                                            onClick={this.onClickReductionBtn}>
                                            {this.props.intl.formatMessage({
                                                id: 'newPanel.operation.reduction',
                                                defaultMessage: '还原'
                                            })}
                                        </Button> : <Button
                                            className={styles.selectRepeatBtn}
                                            size="small"
                                            onClick={this.onClickRepeatBtn}>
                                            {this.props.intl.formatMessage({
                                                id: 'newPanel.operation.repeat',
                                                defaultMessage: '查重'
                                            })}
                                        </Button>}</Col></Row>}>
                                        <Table
                                            className="white-space-nowrap"
                                            rowClassName={this.rowClassName}
                                            rowSelection={rowSelection}
                                            rowKey="id"
                                            columns={columns}
                                            pagination={false}
                                            dataSource={newdetails}
                                            scroll={{
                                                x: 'max-content',
                                                y: 430}}
                                            size="small"
                                            bordered={true} />
                                    </Card>
                                </Form>
                            </Panel>
                        </Collapse>
                    </Card>
                    <Card
                        className={styles.marginBottom}
                        title={this.props.intl.formatMessage({
                            id: 'upPiPanel.card.title',
                            defaultMessage: '审核信息'
                        })}>
                        <Row>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem label={this.props.intl.formatMessage({
                                    id: 'upPiPanel.form.financeApproverName',
                                    defaultMessage: '财务审核人姓名'
                                })} {...FORM_OPTIONS.item}>
                                    {this.props.conditions.financeApproverName}
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem label={this.props.intl.formatMessage({
                                    id: 'upPiPanel.form.financeApproveTime',
                                    defaultMessage: '财务审核时间'
                                })} {...FORM_OPTIONS.item}>
                                    {this.props.conditions.financeApproveTime}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row>
                            <Col {...FORM_BIG_OPTIONS.col}>
                                <FormItem className={styles.multiLabel} label={this.props.intl.formatMessage({
                                    id: 'upPiPanel.form.financeApproveOpinion',
                                    defaultMessage: '财务审核意见'
                                })} {...FORM_BIG_OPTIONS.item}>
                                    {this.props.conditions.financeApproveOpinion}
                                </FormItem>
                            </Col>
                        </Row>
                    </Card>
                    <Card title={this.props.intl.formatMessage({
                        id: 'add.card.fileList.title',
                        defaultMessage: '附件清单'
                    })}>
                        <Row>
                            <Col {...FORM_BIG_OPTIONS.col}>
                                <FileUpload onChange={this.onChangeUpload} onRemove={this.props.removeAttachments} fileList={attachments} />
                            </Col>
                        </Row>
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat}
                        onConfirm={this.props.onCancel} />
                </div>
                <Card type="inner">
                    <Row>
                        <Col className="col-align-right">
                            <Button key="upPi" loading={this.state.loading}
                                onClick={this.submit} type="primary">{this.props.intl.formatMessage({
                                    id: 'upPiPanel.btn.submit',
                                    defaultMessage: '提交'
                                })}</Button>
                        </Col>
                    </Row>
                </Card>
            </div>
        );
    }
}

UpPiPanel.propTypes = {
    conditions: PropTypes.object.isRequired,
    init: PropTypes.func.isRequired,
    loading: PropTypes.bool.isRequired,
    removeAttachments: PropTypes.func.isRequired,
    submitable: PropTypes.bool.isRequired,
    updateAttachments: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onClickUpPi: PropTypes.func.isRequired,
    onUmount: PropTypes.func.isRequired,
    intl: PropTypes.object,
    isMoneyVisible: PropTypes.bool,
    showBrand: PropTypes.bool,
};

import {connect} from 'react-redux';
import {
    getDetail,
    clearData,
    tableSearch,
    onClickUpPi,
    updateAttachments,
    removeAttachments,
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';
import {PERMISSION} from './constants';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
// const getDetailData = selectorFactory(['page', 'domainData', 'detail', 'data']);
const getSubmitData = selectorFactory(['page', 'appState', 'submitData']);
const getSubmitable = createSelector(
    state => getPermissions(state),
    state => state.getIn(['page', 'domainData', 'detail', 'data']),
    (permission, detail) => {
        const {options = []} = detail;
        return options.includes(PERMISSION.approve) && permission.includes(PERMISSION.approve);
    }
);
const mapStateToProps = (state, ownProps) => ({
    loading: state.getIn((['page', 'domainData', 'detail', 'isFetching'])) || state.getIn(['page', 'domainData', 'initData', 'isFetching']),
    isDealerUser: state.getIn(['page', 'domainData', 'initData', 'isDealerUser']),
    // detail: getDetailData(state),
    conditions: getSubmitData(state),
    submitable: getSubmitable(state, ownProps),
    showBrand: state.getIn(['page', 'domainData', 'brands', 'data']).size > 1,
    isMoneyVisible: state.getIn((['page', 'domainData', 'initData', 'isMoneyVisible'])),
});

const mapDispatchToProps = (dispatch, ownProps) => ({
    init: () => dispatch(getDetail(ownProps.id)),
    onCancel: () => {
        ownProps.history.push(routes.query.url());
    },
    updateAttachments: data => dispatch(updateAttachments(data)),
    removeAttachments: ({id}) => dispatch(removeAttachments(id)),
    onClickUpPi: data => dispatch(onClickUpPi(ownProps.id, data)).then(success => {
        if(success) {
            dispatch(tableSearch({
                pageIndex: PAGE.index
            }));
            ownProps.history.push(routes.query.url());
        }
        return success;
    }),
    onUmount: () => dispatch(clearData()),
});

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(UpPiPanel));
